﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.ServiceModel.Channels;
using System.Text;
using System.Threading.Tasks;
using System.ServiceModel;
using Microsoft.WindowsAzure.ServiceRuntime;

namespace AzureUtilities
{
    /// <summary>
    /// The role load balancer is used by an azure instance that needs to communicate with a different role in a load 
    /// balanced way
    /// </summary>
    public static class RoleLoadBalancer
    {
        private static readonly Random _random = new Random();

        /// <summary>
        /// Returns an endpoint from a random instance that belongs to the specified role
        /// </summary>
        /// <param name="role">The role to get an instance of</param>
        /// <param name="endpoint">the name of the endpoint that will be returned</param>
        /// <returns></returns>
        public static RoleInstanceEndpoint GetEndpointForRole(string role, string endpoint)
        {
            Role selectedRole; 
            if(RoleEnvironment.Roles.TryGetValue(role, out selectedRole))
            {
                if (selectedRole.Instances.Any())
                {
                    var randomInstance = selectedRole.Instances[_random.Next(selectedRole.Instances.Count)];
                    RoleInstanceEndpoint foundEndpoint; 
                    if (randomInstance.InstanceEndpoints.TryGetValue(endpoint, out foundEndpoint))
                    {
                        return foundEndpoint;
                    }

                    throw new InvalidOperationException(
                        string.Format("the endpoint {0} does not exist on the selected role ({1}", endpoint, role));
                }

                throw new InvalidOperationException(String.Format("the role {0} doesn't have any instances running", role));

            }

            throw new InvalidOperationException(string.Format("the role {0} is not in the current environment", role));
        }
    }
}
